import UIKit

public class NowcoderTagHandler {
    // MARK: - 支持的视图类型
    public enum ViewType: String {
        case button
        case avatar
        case badge
        case tag
        case custom
    }
    
    // MARK: - 参数解析
    public struct ViewAttributes {
        let type: ViewType
        let params: [String: String]
        
        init?(from attributes: [String: String]) {
            // 检查是否包含 nowcoder class
            guard let classes = attributes["class"]?.components(separatedBy: " "),
                  classes.contains("nowcoder") else {
                return nil
            }
            
            // 解析视图类型
            if let typeStr = attributes["data-type"],
               let viewType = ViewType(rawValue: typeStr) {
                self.type = viewType
            } else {
                self.type = .custom
            }
            
            // 收集其他参数
            self.params = attributes.filter { key, _ in
                key != "class" && key != "data-type"
            }
        }
    }
    
    // MARK: - 视图生成
    public static func createView(attributes: [String: String], content: String) -> UIView? {
        guard let viewAttrs = ViewAttributes(from: attributes) else {
            return nil
        }
        
        switch viewAttrs.type {
        case .button:
            return createButton(params: viewAttrs.params, content: content)
        case .avatar:
            return createAvatar(params: viewAttrs.params)
        case .badge:
            return createBadge(params: viewAttrs.params, content: content)
        case .tag:
            return createTag(params: viewAttrs.params, content: content)
        case .custom:
            return createCustomView(params: viewAttrs.params, content: content)
        }
    }
    
    // MARK: - 具体视图创建
    private static func createButton(params: [String: String], content: String) -> UIView {
        let button = UIButton(type: .system)
        button.setTitle(content, for: .normal)
        
        // 处理参数
        if let color = params["color"] {
            button.setTitleColor(UIColor(hex: color), for: .normal)
        }
        if let bgcolor = params["bgcolor"] {
            button.backgroundColor = UIColor(hex: bgcolor)
        }
        if let radius = params["radius"] {
            button.layer.cornerRadius = CGFloat(Double(radius) ?? 4)
        }
        
        // 设置大小
        let width = CGFloat(Double(params["width"] ?? "0") ?? 0)
        let height = CGFloat(Double(params["height"] ?? "0") ?? 0)
        
        if width > 0 && height > 0 {
            button.frame = CGRect(x: 0, y: 0, width: width, height: height)
        } else {
            button.sizeToFit()
        }
        
        return button
    }
    
    private static func createAvatar(params: [String: String]) -> UIView {
        let imageView = UIImageView()
        
        // 设置大小
        let size = CGFloat(Double(params["size"] ?? "40") ?? 40)
        imageView.frame = CGRect(x: 0, y: 0, width: size, height: size)
        
        // 设置圆角
        imageView.layer.cornerRadius = size / 2
        imageView.clipsToBounds = true
        
        // 设置默认占位图
        let placeholderImage = UIImage(systemName: "person.circle.fill")?
            .withTintColor(.systemGray4, renderingMode: .alwaysOriginal)
        imageView.image = placeholderImage
        
        // 加载图片
        if let urlString = params["url"],
           let url = URL(string: urlString) {
            ImageLoader.shared.loadImage(
                from: url,
                placeholder: placeholderImage
            ) { result in
                switch result {
                case .success(let image):
                    imageView.image = image
                case .failure(let error):
                    print("Failed to load avatar image: \(error)")
                    imageView.image = placeholderImage
                }
            }
        }
        
        return imageView
    }
    
    private static func createBadge(params: [String: String], content: String) -> UIView {
        let label = PaddingLabel()
        label.text = content
        label.font = .systemFont(ofSize: CGFloat(Double(params["font-size"] ?? "12") ?? 12))
        label.textColor = UIColor(hex: params["color"] ?? "#FFFFFF")
        label.backgroundColor = UIColor(hex: params["bgcolor"] ?? "#FF6B6B")
        label.layer.cornerRadius = CGFloat(Double(params["radius"] ?? "10") ?? 10)
        label.clipsToBounds = true
        label.textAlignment = .center
        label.padding = UIEdgeInsets(top: 2, left: 6, bottom: 2, right: 6)
        label.sizeToFit()
        return label
    }
    
    private static func createTag(params: [String: String], content: String) -> UIView {
        let container = UIView()
        
        // 创建标签文本
        let label = UILabel()
        label.text = content
        label.font = .systemFont(ofSize: CGFloat(Double(params["font-size"] ?? "14") ?? 14))
        label.textColor = UIColor(hex: params["color"] ?? "#666666")
        
        // 创建可选的图标
        if let iconName = params["icon"] {
            let imageView = UIImageView(image: UIImage(systemName: iconName))
            imageView.tintColor = label.textColor
            
            container.addSubview(imageView)
            container.addSubview(label)
            
            // 使用 SnapKit 设置约束
            imageView.snp.makeConstraints { make in
                make.left.centerY.equalToSuperview()
                make.size.equalTo(CGSize(width: 16, height: 16))
            }
            
            label.snp.makeConstraints { make in
                make.left.equalTo(imageView.snp.right).offset(4)
                make.top.bottom.right.equalToSuperview()
            }
        } else {
            container.addSubview(label)
            label.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        
        return container
    }
    
    private static func createCustomView(params: [String: String], content: String) -> UIView {
        // 可以根据需要实现自定义视图
        let view = UIView()
        // ... 自定义实现
        return view
    }
}
